//
//  LTLoginViewController.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/3/30.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "LTLoginViewController.h"
#import "LTLoginAPIManager.h"
//#import "LoginHistoryAccountView.h"

@interface LTLoginViewController ()<UITextFieldDelegate ,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)UIView *tableHeaderView;

@property(nonatomic ,strong)UIView *tableFootorView;

@property(nonatomic ,strong)YYLabel *protocolLabel;

@property(nonatomic ,strong)UIButton *protocolSelectButton;

@property(nonatomic ,strong)UIButton *loginButton;

@property(nonatomic ,strong)UITextField *accountTextFiled;

@property(nonatomic ,strong)UITextField *passwordTextFiled;

@property(nonatomic ,strong)UITextField *veriftyTextFiled;


@property(nonatomic ,strong)WKWebView *captchaWeb;

@property(nonatomic ,strong)NSMutableURLRequest *captchaRequest;

@property(nonatomic ,copy)NSString *captcha_token;

@property(nonatomic ,strong)UIImageView *headerBgImageView;

@end

@implementation LTLoginViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.HidenNavigationBar = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.HidenNavigationBar = NO;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.view addSubview:self.headerBgImageView];
    [self.view addSubview:self.tableView];
    

    [BaseRequest checkoutNetWorkStatus:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [self reloadWeb];
        }
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0,0,LTScreenWidth,16);
    label.numberOfLines = 0;
    label.text = @"全国服务热线（400-0755-330）";
    label.textColor = rgba(209, 210, 212, 1);
    label.font = RFontWithSize(14);
    [self.view addSubview:label];
    label.textAlignment = NSTextAlignmentCenter;
    label.y = LTScreenHeight - LTBottomDangerousAreaHeight - label.height - 10;
    
    
}
#pragma mark -API
-(void)doLogin
{
    NSMutableDictionary *dic = @{@"captcha":self.veriftyTextFiled.text,@"captcha_token":self.captcha_token,@"password":self.passwordTextFiled.text,@"account":self.accountTextFiled.text}.mutableCopy;
    [dic setObject:@"1" forKey:@"type"];
    [LTLoginAPIManager loginWithParam:dic result:^(NSDictionary * _Nonnull dic) {
                if([dic[@"code"] intValue] == 0)
                {
                    [self reloadWeb];
                    if (dic[@"msg"]) {
                        [SVProgressHUD showErrorWithStatus:dic[@"msg"]];
                    }
                }
                if([dic[@"code"] intValue] == 1)
                {
                   
                    if(dic[@"data"][@"userinfo"])
                    {
                        [LTApp goHome];
                        USER_DEFAULTS_SAVE(USER_LOGIN_INFO, [dic[@"data"][@"userinfo"] modelToJSONString]);
                    }
                   
                }
    }];
    

}

#pragma mark -UITableViewDelegate,UITableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =nil;
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    [cell.contentView removeAllSubviews];
    if(indexPath.row == 0)
    {
        [cell.contentView addSubview:self.accountTextFiled];
    }else if (indexPath.row == 1)
    {
        [cell.contentView addSubview:self.passwordTextFiled];
    }else{
        [cell.contentView addSubview:self.veriftyTextFiled];
    }
    
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
        return 3;
        
  
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 65;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


}

#pragma mark -UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    //[[textField viewWithTag:1001] setBackgroundColor:kOrangeLineColor];
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    //[[textField viewWithTag:1001] setBackgroundColor:kLineColor];
    
    return  YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}
#pragma mark - private
- (void)goProtocolDetailWithKind:(NSDictionary *)parame
{
    UIViewController *vc = [[UIViewController alloc] initWithClassName:@"LTProtocolShowViewController"];
    vc.paraObject = parame;
    [self.navigationController pushViewController:vc animated:YES];
}
//- (void)changeLoginBtnStatue
//{
//    BOOL canLogin = NO;
//    if(self.protocolSelectButton.selected&&self.accountTextFiled.text.length > 0&&self.passwordTextFiled.text.length > 0)
//    {
//        canLogin = YES;
//    }
//    
//    
//    if(canLogin)
//    {
//        self.loginButton.selected = YES;
//        self.loginButton.backgroundColor = LTClearColor;
//    }else{
//        self.loginButton.selected = NO;
//        self.loginButton.backgroundColor = rgba(229, 229, 229, 1);
//    }
//    
//}
#pragma mark -event response

- (void)tapClick
{
    [self.view endEditing:YES];
}

- (void)loginButtonAction
{
    [self.view endEditing:YES];
    NSString *str=@"";
    
    
  
    if (!self.protocolSelectButton.selected) {
        str = @"请勾选协议！";
    }
    
    if (self.veriftyTextFiled.text.length == 0) {
        str = @"验证码不能为空！";
    }
    if (self.passwordTextFiled.text.length == 0) {
        str = @"密码不能为空！";
    }
    if (self.accountTextFiled.text.length == 0) {
        str = @"账号不能为空！";
    }
    if(str.length == 0)
    {
        [MethodTool getCookieWithwebView:self.captchaWeb success:^(BOOL success) {
            [self doLogin];
        }];
    }else{
        [SVProgressHUD showImage:nil status:str];
    }
    
}
-(void)goingSelectSchoolAction
{
    [self.view endEditing:YES];
}
-(void)reloadWeb
{
    [self.view endEditing:YES];
    [self.captchaWeb loadRequest:self.captchaRequest];
}


-(void)protocolSelectButtonAction:(UIButton *)sender
{
    sender.selected =!sender.selected;
   
}

-(void)textFieldResignTapAction:(UITapGestureRecognizer *)sender
{
    [self.view endEditing:YES];
}
-(void)textEnd:(UITextField *)textField
{
    [self.tableView reloadData];
}
-(void)textChanged:(UITextField *)textField
{
    
    //[self changeLoginBtnStatue];
}
#pragma mark -getters and setters
-(UITableView *)tableView{
    if (!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -LTStatusBarHeight, LTScreenWidth, LTScreenHeight + LTStatusBarHeight) style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        _tableView.bounces = NO;
        [_tableView setBackgroundColor:LTWhiteColor];
        [_tableView setSeparatorColor:LTClearColor];
        [_tableView setTableHeaderView:self.tableHeaderView];
        [_tableView setTableFooterView:self.tableFootorView];
    }
    
    return _tableView;
}

-(UIView *)tableHeaderView
{
    if (!_tableHeaderView)
    {
        
        _tableHeaderView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, LTScreenWidth,210)];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
            [_tableHeaderView addGestureRecognizer:tap];
        UIImageView *headerBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, LTScreenWidth, 272.00/375*LTScreenWidth)];
        headerBgImageView.image = IMAGENAMED(@"ic_login_bg");
        
        UIImageView *headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(32, 128/375.00*LTScreenWidth, 40, 40)];
        headerImageView.image = IMAGENAMED(@"ic_login_logo");
        [_tableHeaderView addSubview:headerBgImageView];
        [_tableHeaderView addSubview:headerImageView];
    
        UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(32, headerImageView.bottom + 16, LTScreenWidth - 64, 30)];
        titleLabel.font = SFontWithSize(24);
        titleLabel.text = @"习堂";
        [titleLabel setTextAlignment:NSTextAlignmentLeft];
        titleLabel.textColor = LTTextBlack;
        
        UILabel * subLabel = [[UILabel alloc] initWithFrame:CGRectMake(32, titleLabel.bottom + 6, LTScreenWidth - 64, 18)];
        subLabel.font = RFontWithSize(13);
        subLabel.text = @"您好！欢迎使用习堂 (教师端)";
        [subLabel setTextAlignment:NSTextAlignmentLeft];
        subLabel.textColor = rgba(102, 102, 102, 1);
        [_tableHeaderView addSubview:titleLabel];
        [_tableHeaderView addSubview:subLabel];
        
        _tableHeaderView.height = headerBgImageView.bottom + 11;
       
    }
    
    return _tableHeaderView;
}

-(UIView *)tableFootorView
{
    if (!_tableFootorView)
    {
        _tableFootorView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, LTScreenWidth - 20, 20)];
        [_tableFootorView addSubview:self.loginButton];
        [_tableFootorView addSubview:self.protocolSelectButton];
        [_tableFootorView addSubview:self.protocolLabel];
        [self.protocolSelectButton setY:self.loginButton.bottom + 5];
        [self.protocolLabel setY:self.loginButton.bottom + 15];
        _tableFootorView.height = self.protocolLabel.bottom;
        
    }
    
    return _tableFootorView;
}

- (UIImageView *)headerBgImageView
{
    if(!_headerBgImageView)
    {
        _headerBgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, LTScreenWidth, 313.0/375*LTScreenWidth)];
        _headerBgImageView.image = IMAGENAMED(@"ic_login_header_bg");
        
    }
    return _headerBgImageView;
}

-(UIButton *)loginButton
{
    if (!_loginButton)
    {
        _loginButton = [UIButton new];
        _loginButton.frame =CGRectMake(32, 40, LTScreenWidth - 64, 44);
       
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
       // [_loginButton setTitleColor:rgba(181, 181, 181, 1) forState:UIControlStateNormal];
        [_loginButton setTitleColor:LTWhiteColor forState:UIControlStateNormal];
        [_loginButton.titleLabel setFont:MFontWithSize(14)];
        [_loginButton addTarget:self action:@selector(loginButtonAction) forControlEvents:UIControlEventTouchUpInside];
        _loginButton.backgroundColor = rgba(41, 121, 255, 1);
        _loginButton.layer.cornerRadius = 22;
        _loginButton.layer.shadowColor = rgba(41, 121, 255, 0.50).CGColor;
        _loginButton.layer.shadowOffset = CGSizeMake(0,4);
        _loginButton.layer.shadowOpacity = 1;
        _loginButton.layer.shadowRadius = 6;
    }
    
    return _loginButton;
}

-(UIButton *)protocolSelectButton
{
    if (!_protocolSelectButton)
    {
        _protocolSelectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_protocolSelectButton setImage:[UIImage imageNamed:@"ic_protocol_unSelect"] forState:UIControlStateNormal];
        [_protocolSelectButton setImage:[UIImage imageNamed:@"ic_protocol_select"] forState:UIControlStateSelected];
        [_protocolSelectButton addTarget:self action:@selector(protocolSelectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//        _protocolSelectButton.imageEdgeInsets =UIEdgeInsetsMake(15, 0, 15, 10);
        //_protocolSelectButton.imageEdgeInsets =UIEdgeInsetsMake(12.5, 0, 12.5, 5);
        _protocolSelectButton.frame = CGRectMake(32, 5, 26, 40);
        _protocolSelectButton.selected =NO;
    }
    
    return _protocolSelectButton;
}
-(YYLabel *)protocolLabel
{
    if (!_protocolLabel)
    {
        NSMutableAttributedString *text = [NSMutableAttributedString new];
        NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:@"同意"];
        one.color = rgba(181, 181, 181, 1);
        NSMutableAttributedString *two = [[NSMutableAttributedString alloc] initWithString:@"《使用协议》、"];
        NSMutableAttributedString *three = [[NSMutableAttributedString alloc] initWithString:@"《隐私协议》、"];
        NSMutableAttributedString *four = [[NSMutableAttributedString alloc] initWithString:@"《儿童隐私协议》"];
    
        two.font = one.font = three.font = four.font = MFontWithSize(12);
        
        [two setTextHighlightRange:two.rangeOfAll
                             color:rgba(41, 121, 255, 1)
                   backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.220]
                         tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect)
         {
            [self goProtocolDetailWithKind:@{@"teacher_use_agreement":@"使用协议"}];
         }];
        
        [three setTextHighlightRange:three.rangeOfAll
                             color:rgba(41, 121, 255, 1)
                   backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.220]
                         tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect)
         {
            [self goProtocolDetailWithKind:@{@"teacher_privacy_agreement":@"隐私政策"}];
         }];

        [four setTextHighlightRange:four.rangeOfAll
                               color:rgba(41, 121, 255, 1)
                     backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.220]
                           tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect)
         {
            [self goProtocolDetailWithKind:@{@"teacher_protect_agreement":@"儿童隐私保护政策"}];
         }];
        
        [text appendAttributedString:one];
        [text appendAttributedString:two];
        [text appendAttributedString:three];
        [text appendAttributedString:four];
        
        NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 5.0;
        [text addAttribute:NSParagraphStyleAttributeName
                     value:paragraphStyle
                     range:NSMakeRange(0, text.string.length)];
        
        YYLabel *label = [YYLabel new];
        label.numberOfLines =0;
        label.textAlignment =NSTextAlignmentCenter;
        label.attributedText =text;
        label.frame =CGRectMake(self.protocolSelectButton.right + 3, 15, LTScreenWidth - 32 - self.protocolSelectButton.right - 3, 21);
        [label sizeToFit];
        _protocolLabel =label;
    }

    return _protocolLabel;
}


-(UITextField *)veriftyTextFiled
{
    if (!_veriftyTextFiled)
    {
        _veriftyTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(32, 6, LTScreenWidth - 64, 49)];
        _veriftyTextFiled.font = MFontWithSize(16);
        _veriftyTextFiled.textColor = rgba(51, 51, 51, 1);
        _veriftyTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _veriftyTextFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _veriftyTextFiled.delegate =self;
       
        if (@available(iOS 11.0,*)) {
            _veriftyTextFiled.textContentType =UITextContentTypeUsername;
        }
        [_veriftyTextFiled setAllCornersWithCornerRadius:6];
        _veriftyTextFiled.backgroundColor = rgba(247, 248, 250, 1);
        [_veriftyTextFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        UIView *leftSpaceView = [[UIView alloc] init];
        leftSpaceView.frame = CGRectMake(0,0,98,49);
        leftSpaceView.backgroundColor = rgba(247, 248, 250, 1);
        UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 83, 49)];
        titleLabel.font = MFontWithSize(15);
        titleLabel.text = @"验证码";
        [titleLabel setTextAlignment:NSTextAlignmentLeft];
        
        titleLabel.textColor = LTTextBlack;
        [leftSpaceView addSubview:titleLabel];
        
        _veriftyTextFiled.leftViewMode = UITextFieldViewModeAlways;
        _veriftyTextFiled.leftView = leftSpaceView;
        UIView *rightSpaceView = [[UIView alloc] init];
        rightSpaceView.frame = CGRectMake(0,0,100,49);
        rightSpaceView.backgroundColor =rgba(245, 245, 245, 1);
        [rightSpaceView addSubview:self.captchaWeb];
        [self.captchaWeb loadRequest:self.captchaRequest];
        [rightSpaceView addSubview:self.captchaWeb];
        UIButton *relodBtn = [UIButton new];
        relodBtn.frame = CGRectMake(0,0,100,49);;
       
        [rightSpaceView addSubview:relodBtn];
        [relodBtn addTarget:self action:@selector(reloadWeb) forControlEvents:UIControlEventTouchUpInside];
        _veriftyTextFiled.rightViewMode = UITextFieldViewModeAlways;
        _veriftyTextFiled.rightView = rightSpaceView;
        
    }

    return _veriftyTextFiled;
}
- (WKWebView *)captchaWeb
{
    if(!_captchaWeb)
    {
        _captchaWeb = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, 100, 49)];
        
    }
    return _captchaWeb;
}
- (NSMutableURLRequest *)captchaRequest
{
   
   self.captcha_token =  [NSString stringWithFormat:@"%d",arc4random()];
   NSString *url = [NSString stringWithFormat:@"%@%@%@%@",BASE_URL,LOGIN_CAPTCHA_URL,@"?id=",self.captcha_token];
    return [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
}
-(UITextField *)accountTextFiled
{
    if (!_accountTextFiled)
    {
        _accountTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(32, 6, LTScreenWidth - 64, 49)];
        _accountTextFiled.font = MFontWithSize(16);
        _accountTextFiled.textColor = rgba(51, 51, 51, 1);
        _accountTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _accountTextFiled.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入账号" attributes:@{NSFontAttributeName:MFontWithSize(16)}];
        _accountTextFiled.delegate =self;
       // [_accountTextFiled setInputAccessoryView:self.customTextFieldInputAccessoryView];
        if (@available(iOS 11.0,*)) {
            _accountTextFiled.textContentType =UITextContentTypeUsername;
        }
        [_accountTextFiled setAllCornersWithCornerRadius:6];
        _accountTextFiled.backgroundColor = rgba(247, 248, 250, 1);
        [_accountTextFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        [_accountTextFiled addTarget:self action:@selector(textEnd:) forControlEvents:UIControlEventEditingDidEnd];
        UIView *leftSpaceView = [[UIView alloc] init];
        leftSpaceView.frame = CGRectMake(0,0,98,49);
        leftSpaceView.backgroundColor = rgba(247, 248, 250, 1);
        UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 83, 49)];
        titleLabel.font = MFontWithSize(15);
        titleLabel.text = @"账号";
        [titleLabel setTextAlignment:NSTextAlignmentLeft];
        
        titleLabel.textColor = LTTextBlack;
        [leftSpaceView addSubview:titleLabel];
        
        _accountTextFiled.leftViewMode = UITextFieldViewModeAlways;
        _accountTextFiled.leftView = leftSpaceView;
        
    }

    return _accountTextFiled;
}
-(UITextField *)passwordTextFiled
{
    if (!_passwordTextFiled)
    {
        _passwordTextFiled =[[UITextField alloc] initWithFrame:CGRectMake(32, 6, LTScreenWidth - 64, 49)];
        _passwordTextFiled.font = MFontWithSize(16);
        _passwordTextFiled.textColor = rgba(51, 51, 51, 1);
        _passwordTextFiled.clearButtonMode =UITextFieldViewModeWhileEditing;
        _passwordTextFiled.secureTextEntry =YES;
        _passwordTextFiled.delegate =self;
        _passwordTextFiled.placeholder = @"请输入密码";
        [_passwordTextFiled setAllCornersWithCornerRadius:6];
        _passwordTextFiled.backgroundColor = rgba(247, 248, 250, 1);
        //[_passwordTextFiled setInputAccessoryView:self.customTextFieldInputAccessoryView];


        if (@available(iOS 11.0,*)) {
            _passwordTextFiled.textContentType =UITextContentTypePassword;
        }

        [_passwordTextFiled addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
        [_passwordTextFiled addTarget:self action:@selector(textEnd:) forControlEvents:UIControlEventEditingDidEnd];
        UIView *leftSpaceView = [[UIView alloc] init];
        leftSpaceView.frame = CGRectMake(0,0,98,49);
        leftSpaceView.backgroundColor = rgba(247, 248, 250, 1);
        UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 83, 49)];
        titleLabel.font = MFontWithSize(15);
        titleLabel.text = @"密码";
        [titleLabel setTextAlignment:NSTextAlignmentLeft];
        
        titleLabel.textColor = LTTextBlack;
        [leftSpaceView addSubview:titleLabel];
        _passwordTextFiled.leftViewMode = UITextFieldViewModeAlways;
        _passwordTextFiled.leftView = leftSpaceView;
    }

    return _passwordTextFiled;
}

@end
